﻿using System;
using System.Xml;
using System.Collections.Generic;
using System.Text;

using Weazel.Gezel.Model;

namespace Weazel.Gezel.Exporter
{
	internal class SignalFlowGraphExporter
	{
		internal static void ToXml(XmlDocument xmlDoc, XmlElement parent, SignalFlowGraph sfg)
		{
			XmlElement sfgElement = xmlDoc.CreateElement("SignalFlowGraph");

			// name attribute
			XmlAttribute nameAttribute = xmlDoc.CreateAttribute("name");
			nameAttribute.Value = sfg.LocalName;
			sfgElement.Attributes.Append(nameAttribute);

			// id attribute
			XmlAttribute idAttribute = xmlDoc.CreateAttribute("id");
			idAttribute.Value = sfg.Name;
			sfgElement.Attributes.Append(idAttribute);

			if (sfg.Register != null)
			{
				RegisterExporter.ToXml(xmlDoc, sfgElement, sfg.Register);
			}
			
			if (sfg.Signal != null)
			{
				SignalExporter.ToXml(xmlDoc, sfgElement, sfg.Signal);
			}

			foreach (Expression expr in sfg.Expressions)
			{
				if (expr is DirectiveExpression)
				{
					XmlElement directiveExpression = xmlDoc.CreateElement("Directive");

					sfgElement.AppendChild(directiveExpression);
				}
				else
				{
					XmlElement exprElement = xmlDoc.CreateElement("Expression");

					XmlAttribute exprIdAttribute = xmlDoc.CreateAttribute("id");
					exprIdAttribute.Value = sfg.Name;
					exprElement.Attributes.Append(exprIdAttribute);

					exprElement.InnerText = expr.ToString();

					sfgElement.AppendChild(exprElement);
				}
			}

			parent.AppendChild(sfgElement);
		}

    internal static void ToGezel(System.CodeDom.Compiler.IndentedTextWriter textWriter, SignalFlowGraph sfg)
    {
      textWriter.WriteLine("sfg {0}", sfg.LocalName);
      textWriter.WriteLine("{");
      textWriter.Indent++;

      if (sfg.Register != null)
      {
        RegisterExporter.ToGezel(textWriter, sfg.Register);
      }

      if (sfg.Signal != null)
      {
        SignalExporter.ToGezel(textWriter, sfg.Signal);
      }

      foreach (Expression expr in sfg.Expressions)
      {
        textWriter.WriteLine("{0};", expr.ToString());
      }

      textWriter.Indent--;
      textWriter.WriteLine("}");
    }
  }
}
